package com.anjingsi.tools.exception;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class ManagerException extends Exception implements CodeException {
    Code code;
    String msgFormat;
    Object[] params;
    Pattern pattern = Pattern.compile("\\{\\s{0,}\\}");

    public ManagerException(Code code, String msg, Object... params) {
        this.code = code;
        this.msgFormat = msg;
        this.params = params;
    }

    public String getCode() {
        StringBuffer sb = new StringBuffer();
        sb.append(String.format("%04d", this.code.code1));
        sb.append(String.format("%03d", this.code.code2));
        sb.append(String.format("%03d", this.code.code3));
        return sb.toString();
    }

    public String getMessage() {
        if (this.msgFormat == null) {
            return "";
        } else {
            Matcher matcher = this.pattern.matcher(this.msgFormat);
            StringBuffer sb = new StringBuffer();
            List<String> replaceStr = Collections.emptyList();
            if (this.params != null) {
                replaceStr = (List) Arrays.asList(this.params).stream().map((p) -> {
                    return p != null ? p.toString() : "";
                }).collect(Collectors.toList());
            }

            for(int index = 0; replaceStr.size() > index && matcher.find(); ++index) {
                matcher.appendReplacement(sb, (String)replaceStr.get(index));
            }

            matcher.appendTail(sb);
            return sb.toString();
        }
    }
}